"use client"

import { Button } from "@/components/ui/button"
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage
} from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import { zodResolver } from "@hookform/resolvers/zod"
import { useForm } from "react-hook-form"
import { z } from "zod"
import {
  Card,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
} from "@/components/ui/card"
import { signIn } from "next-auth/react"
import { useState } from "react"
import { useRouter } from "next/navigation"

// 定义登录表单验证模式
const loginFormSchema = z.object({
  username: z.string().min(1, {
    message: "用户名不能为空",
  }),
  password: z.string().min(1, {
    message: "密码不能为空",
  }),
})

export type LoginFormSchemaType = z.infer<typeof loginFormSchema>;

export default function Page() {
  const router = useRouter();
  const [error, setError] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(false);

  const form = useForm<LoginFormSchemaType>({
    resolver: zodResolver(loginFormSchema),
    defaultValues: {
      username: "",
      password: ""
    }
  })

  // 处理表单提交
  async function onSubmit(values: LoginFormSchemaType) {
    setIsLoading(true);
    setError(null);

    try {
      const result = await signIn("credentials", {
        username: values.username,
        password: values.password,
        redirect: false,
      });

      if (result?.error) {
        setError(result.error);
        return;
      }

      // 登录成功，跳转到首页
      window.location.href = "/";
    } catch (error) {
      setError("登录过程中发生错误，请稍后重试");
      console.error(error);
    } finally {
      setIsLoading(false);
    }
  }

  return <div className='py-[100px] w-full bg-gradient-to-br from-lime-400 to-cyan-400 h-screen flex items-center justify-center'>
    <Form {...form}>
      <form
        className="p-[20px] w-[420px]"
        onSubmit={form.handleSubmit(onSubmit)}
      >
        <Card className="w-[350px]">
          <CardHeader>
            <CardTitle>账号登录</CardTitle>
            <CardDescription>请输入您的用户名和密码</CardDescription>
          </CardHeader>
          <CardContent>
            {error && (
              <div className="bg-red-50 text-red-500 px-3 py-2 rounded-md mb-4 text-sm">
                {error}
              </div>
            )}
            <FormField
              control={form.control}
              name="username"
              render={({ field }) => (
                <FormItem className="mb-4">
                  <FormLabel>用户名</FormLabel>
                  <FormControl>
                    <Input placeholder="请输入用户名" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="password"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>密码</FormLabel>
                  <FormControl>
                    <Input type="password" placeholder="请输入密码" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
          </CardContent>
          <div className="text-center text-sm">
              没有账号？<a href="/sign-up" className="text-blue-600 hover:underline">去注册</a>
            </div>
          <CardFooter>
            <Button type="submit" className="w-full" disabled={isLoading}>
              {isLoading ? "登录中..." : "登录"}

            </Button>
          </CardFooter>
        </Card>
      </form>
    </Form>
  </div>
}